package UsersPackage;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register.do")
public class RegisterServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        request.setCharacterEncoding("UTF-8");
        try {
            request.setCharacterEncoding("UTF-8");
            response.setCharacterEncoding("UTF-8");
            String username = request.getParameter("username");
            String user_id = request.getParameter("user_id");
            String password = request.getParameter("password");
            String email = request.getParameter("email");
            String birth = request.getParameter("birth");
            String phone = request.getParameter("phone");

            String address = request.getParameter("address");

            UserDao userService = new UserDao();
            //这一段利用UserDao要大于0才算成功所以不能删
            // 检测user_id注册
            if (userService.isUserIdExists(user_id)) {
                response.getWriter().print("用户名已存在.请重新输入(将等待3秒后跳转)");
                // 添加以下代码来进行页面重定向
                response.setHeader("Refresh", "3;url=Register.jsp"); // 在3秒后跳转回登录页面
            }else
            // 检测username注册
            if (userService.isUsernameExists(username)) {
                response.getWriter().print("账号已存在.请重新输入(将等待3秒后跳转)");
                // 添加以下代码来进行页面重定向
                response.setHeader("Refresh", "3;url=Register.jsp"); // 在3秒后跳转回登录页面
            }
            else if(userService.register(username, user_id, password, email, birth, phone, address) > 0) {
                response.getWriter().print("注册成功!");
            }else {
                response.getWriter().print("注册失败!");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
}
